<script lang="ts" setup>
import type { AppForm } from '@/api/app/types'
import type { FormInstance, FormRules } from 'element-plus';
import * as app from '@/api/app';

const formRef = ref<FormInstance>()

const defaultFormData = () => ({
    name: '',
    code: '',
    platform: undefined
})

const formData = ref<AppForm>(defaultFormData())

const formRules = reactive<FormRules<AppForm>>({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入编码', trigger: 'blur' }
    ],
    platform: [
        { required: true, message: '请选择操作系统', trigger: 'change' }
    ]
})

const plarformOptions = ref<OptionItem[]>()

onBeforeMount(async () => {
    plarformOptions.value = await app.platformOptions()
})

const props = reactive<ModalWindowProp>({
    title: '',
    visible: false,
    context: undefined
})

const open = async (dialogProps: ModalWindowProp) => {
    if(dialogProps.context === undefined) {
        formData.value = defaultFormData()
    } else {
        props.context = dialogProps.context
        formData.value = await app.get(dialogProps.context)
    }
    
    props.title = dialogProps.title
    props.visible = true
}

defineExpose({
    open
})

const emit = defineEmits(['close'])

const submit = async () => {
    if(!formRef.value) {
        return
    }

    await formRef.value.validate(async (valid) => {
        if(valid) {
            let result: ApiResult
            if(props.context === undefined) {
                result = await app.add(formData.value)
            } else {
                result = await app.edit(props.context, formData.value)
            }
            
            if(result.success) {
                ElMessage.success(result.message)
                props.visible = false
                emit('close')
            } else {
                ElMessage.error(result.message)
            }
        }
    })
}
</script>

<template>
    <el-dialog v-model="props.visible" :title="props.title">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
            <el-form-item prop="name" label="名称">
                <el-input v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item prop="code" label="编码">
                <el-input v-model="formData.code"></el-input>
            </el-form-item>
            <el-form-item prop="platform" label="操作系统">
                <el-select v-model="formData.platform" placeholder="请选择操作系统">
                    <el-option v-for="option in plarformOptions" :key="option.value" :value="option.value" :label="option.label"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="submit">保存</el-button>
        </template>
    
    </el-dialog>
</template>

<styple lang="scss" scoped>

</styple>